package cn.chendd.shiro.custom;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义用户、角色、权限认证器
 * @author chendd
 */
public class PrimisionRealm extends IniRealm {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String getName() {
        return "chendd-primision-realm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo author = new SimpleAuthorizationInfo();
        String userName = (String) principals.getPrimaryPrincipal();
        logger.debug("###构造用户[{}]的角色权限授权信息###" , userName);
        Set<String> roles = new HashSet<>();//角色集合
        Set<String> primisions = new HashSet<>();//权限集合
        if("admin".equals(userName)){
            roles.add("admin");//管理员角色，任意权限
            primisions.add("*");
        } else if("chendd".equals(userName)){
            roles.add("coder");//coder角色及权限
            primisions.add("usermanager:*");
            primisions.add("logmanager:select");
            primisions.add("menumanager:insert");
            primisions.add("menumanager:delete");
            roles.add("tester");//tester角色及权限
            primisions.add("menumanager:test:test");
            primisions.add("menumanager:insert");
        } else if("tt".equals(userName)){
            roles.add("tester");//tester角色及权限
            primisions.add("menumanager:test:test");
            primisions.add("menumanager:insert");
        } else {
            throw new AuthenticationException("用户名与密码不匹配！");
        }
        author.addRoles(roles);
        author.addStringPermissions(primisions);
        return author;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        String userName = userToken.getUsername();
        String password = new String(userToken.getPassword());
        boolean flag = false;
        if("admin".equals(userName) && "admin123".equals(password)){
            flag = true;
        } else if("chendd".equals(userName) && "chendd123".equals(password)){
            flag = true;
        } else if("tt".equals(userName) && "tt123".equals(password)){
            flag = true;
        } else {
            throw new AuthenticationException("用户名与密码不匹配！");
        }
        AuthenticationInfo authent = new SimpleAuthenticationInfo(token.getPrincipal() , token.getCredentials() , this.getName());
        return authent;
    }
}
